package com.dsx.test.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * @author : tianwenqing
 * @version : 1.0
 * @date : 2020-11-16 19:14
 * @description :
 **/
@Component
@Slf4j
public class JwtRealm extends AuthorizingRealm {


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomizedToken ;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userId = (String) principalCollection.getPrimaryPrincipal();
        //根据用户ID,查询角色，权限
        Set<String> roles = null ;
        Set<String> permissions = new HashSet<>();
        permissions.add("/api/perm");
        // 设置授权对象
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        auth.setStringPermissions(permissions);
        auth.setRoles(roles);
        return auth ;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //登录的时候设置的AuthenticationToken 为 customizedToken
        CustomizedToken customizedToken = (CustomizedToken) authenticationToken;

        String token = (String) customizedToken.getCredentials();
        String userId = (String) customizedToken.getPrincipal();

        //校验token
        if(StringUtils.isBlank(token)){

        }

        //校验userId
        if(StringUtils.isBlank(userId)){

        }

        //验证用户信息

        return new SimpleAuthenticationInfo(userId,token,getName());
    }
}
